package net

import (
	"bytes"
	"fmt"
	"github.com/gogf/gf/v2/util/gutil"
)

const (
	EventTypeMsg    = "message"
	EventTypeDone   = "done"
	EventTypeError  = "error"
	EventTypeFailed = "failed"
)

type Event struct {
	Id    string // 消息 ID
	Event string // 事件类型 默认 message
	Data  string // 消息内容
	Retry uint   // 重连时间 默认 3s
	Eof   bool   // 是否最后消息
}

func (r *Event) setEvent(eof bool) {
	if gutil.IsEmpty(r.Event) {
		if eof {
			r.Event = EventTypeDone
		} else {
			r.Event = EventTypeMsg
		}
	}
}
func (r *Event) prepareMessage() []byte {
	var data bytes.Buffer

	if len(r.Id) > 0 {
		data.WriteString(fmt.Sprintf("id: %s\n", r.Id))
	}
	if len(r.Event) > 0 && r.Event != EventTypeMsg {
		data.WriteString(fmt.Sprintf("event: %s\n", r.Event))
	}
	if r.Retry > 0 && r.Retry != 3000 {
		data.WriteString(fmt.Sprintf("retry: %d\n", r.Retry))
	}
	if len(r.Data) > 0 {
		data.WriteString(fmt.Sprintf("data: %s\n", r.Data))
	}
	if r.Eof {
		if gutil.IsEmpty(r.Event) {
			data.WriteString("event: eof\n")
		}
		if gutil.IsEmpty(r.Data) {
			data.WriteString("data: End of events\n")
		}
	}

	data.WriteString("\n")

	return data.Bytes()
}
